1. Report with R Markdown - Theory

1 Introduction

R Markdown is an authoring framework for data science (AFDS) combining R code with narrative text. AFDS permits to create a computational document, with a notebook interface for report generation. There are other AFDS like Jupyter in Python, D3.js and Plotly both in JavaScript.

AFDS Description Description
Rmarkdown R front-end oriented
Jupyter Python back-end oriented
D3.js JavaScript web oriented
Plotly JavaScript web oriented

R Markdown use Markdown syntax, supports HTML/CSS tags, BibTex bibliographic references, 3D charts. The main R Markdown packages are:

  • {rmarkdown} dynamic document
  • {knitr} designed to be a ‘transparent engine for dynamic report generation with R(Xie 2022)
  • {bookdown} advanced editing and publishing functions
  • {tinytex} for LaTeX syntax

1.1 Create a new document

In RStudio:
File > New file > R Markdown...

The parameters (Title, Author) can be changed later on the YAML header

A new document is created:

Run the new document with knit

2 Document structure

R Markdown combines:

YAML header

narrative part

R code

narrative part

R code

2.1 Narrative parts

Narrative parts required principally the use of the Markdown syntax, but also supports HTML/CSS code, LaTeX syntax, etc.

2.1.1 Markdown syntax

Markdown is an easy-to-write plain text syntax used by different code-oriented frameworks:

Markdown basic syntax
Markdown online editor

Images

These coding give the same results (Markdown and HTML):

  • online images
![](https://raw.githubusercontent.com/zoometh/oxford/main/R4A/www/logo.png){width=500px}  
<img align="center" src="https://raw.githubusercontent.com/zoometh/oxford/main/R4A/www/logo.png" alt="" width=500>  


  • local images
![](www/logo.png){width=500px}  
<img align="center" src="www/logo.png" alt="" width=500>  


Titles

# Header level 1

## Heading level 2

### Heading level 3

etc.

Avoid numbering of titles:

#### Spaces and end of lines {-}

Add an anchor

#### Bookmarks {-#bookmarks}

Spaces and end of lines

Extra spaces (HTML tags)

  • &emsp; means 4 spaces (= a tabulation)
  • &ensp; means 2 spaces
  •   &nbsp; means 1 space

End of line (<br> in HTML) with 2 or more spaces and return, for example:

'Reconnais-toi  
Cette adorable personne c'est toi  
Sous le grand chapeau canotier  
Oeil
Nez  
Ta Bouche  
Voici l’ovale de ta figure  
Ton cou Exquis' (Apollinaire, 1913) 

‘Reconnais-toi
Cette adorable personne c’est toi
Sous le grand chapeau canotier
Oeil Nez
Ta Bouche
Voici l’ovale de ta figure
Ton cou Exquis’ (Apollinaire, 1913)

Styling text

code in R Markdown Output
**bold**, __bold__ bold, bold
*italic*, _italic_ italic, italic
code code
hyphen -- inserted -- in a sentence hyphen – inserted – in a sentence
H~2~O H2O
10^−19^ 10−19
$$\sum_{i=1}^{n} X^3_i$$ \[\sum_{i=1}^{n} X^3_i\]
  • comments >

> I am commented

I am commented

  • line separator
--- or ***

A extended part of the text styling can also be done with HTML/CSS

Lists

- numbered  
  
  1. first element
  2. second element
  3. third element 
  • numbered

    1. first element
    2. second element
    3. third element
- bullet
  
  * first element
  * second element
  * third element
    - third element - sub 1
    - third element - sub 2
      + third element - sub 2 - subsub 1
      + third element - sub 2 - subsub 2
  • bullet

    • first element
    • second element
    • third element
      • third element - sub 1
      • third element - sub 2
        • third element - sub 2 - subsub 1
        • third element - sub 2 - subsub 2

Tables

  • simple table
| Syntax | Description |
| --- | ----------- |
| Header | Title |
| Paragraph | Text |

and

| Syntax      | Description |
| ----------- | ----------- |
| Header      | Title       |
| Paragraph   | Text        |

produce the same result:

Syntax Description
Header Title
Paragraph Text
  • alignements
| Left        |    Center   |         Rigth |
| :---        |    :----:   |          ---: |
| Header      | Title       | Here's this   |
| Paragraph   | Text        | And more      |
Left Center Rigth
Header Title Here’s this
Paragraph Text And more

  Table are often data structure difficult to layout. For complex tables you will need to use code chunks, e.g. kable() from {knitr} with kable_styling() from {kableExtra}

Bookmarks

After this theoretical part, you will have to [practice](#practice)
After this theoretical part, you will have to practice

The reference section, ‘Practice,’ appears like that:

rmd_yaml_bib

Footnotes

Add footnote to the bottom of the document

A simple footnote,[^1] or a longer one.[^bignote]
A simple footnote,1 or a longer one.2

[^1]: This is the first footnote.

[^bignote]: Here's one with multiple paragraphs and code.

    Indent paragraphs to include them in the footnote.

    `{ my code }`

    Add as many paragraphs as you like.

2.1.2 Cross-referencing

Cite and reuse variables, figures, tables, sections, etc., through your document

  In the following verbatim parts, replace by the back quote symbol `

Variables

library(archdata)
data("Handaxes")
number.of.axes <- nrow(Handaxes)
'(...) the Furze Platt dataset counts 'r number.of.axes' described by 'r ncol(Handaxes)'. The maximal length (L = 'r max(Handaxes$L)')  (...)'  

‘(…) the Furze Platt dataset counts 600 described by 8. The maximal length (L = 242) (…)’

Figures

library(archdata)
data("Handaxes")
plot(Handaxes$L, Handaxes$B)
model <- lm(B ~ L, data = Handaxes)
abline(lm(model))
Maximum Length/Maximum breadth in cm

Figure 2.1: Maximum Length/Maximum breadth in cm

'(...) the distribution of the maximum length (L) and maximum breadth (B) shows a R^2^ = 'r round(model$coefficients[2], 2)',  Fig. \@ref(fig:maxLmaxB)) (...)'  

‘(…) the distribution of the maximum length (L) and maximum breadth (B) shows a R2 = 0.42, Fig. 2.1) (…)’

Sections

See section [**Bookmarks**](#bookmarks)
See section Bookmarks

2.1.3 Bibliographic references

  • file .bib referenced in the YAML header

rmd_yaml_bib

rmd_bib

  • cross citation in text
code in R Markdown Output
@Xie22 Xie (2022)
[@Xie22] (Xie 2022)
[credits: @Xie22] (credits: Xie 2022)
published by Yihui Xie [-@Xie20; -@Xie22] published by Yihui Xie (2020; 2022)

Bibliographies and citations (Xie, Dervieux, and Riederer 2020)

2.2 Code parts

Code chunks, or chunks, are the placeholders for the coding part of the document

2.2.2 Body

The body of a code chunk is where you place the R code you have scripted

2.3 Header part

This is the YAML header, it contains the metadata and the document configuration.

3 HTML/CSS

Can be use in all parts of the document (YAML header, code chunks, narrative parts)

3.1 Styling

code in R Markdown (= HTML) Output
<span style='font-size: 30px'>Big font</span> Big font
<b>bolded</b> bolded
<span style="color:red">color</span> color

Customize the document with CSS layouts like <notes>this CSS element with a dodgerblue for background and white for text</notes> here: https://github.com/zoometh/oxford/blob/main/R4A/styles.css Customize the document with CSS layouts like this CSS element with a dodgerblue for background and white for text

The CSS file is here: https://github.com/zoometh/oxford/blob/main/R4A/styles.css CSS online editor, e.g. fonts

3.2 Interactivity

The interest of HTML is its ability to be deployed online, with interactive settings. R offers a real framework to create interactive documents, Shiny. Shiny can be integrated into R Markdown

  • try: File > New File > Rmarkdown > Shiny, or
  • in the YAML header:
    runtime: shiny`

3.2.1 Maps

With the {leaflet} package

library(dplyr)
library(leaflet)
munsingen.long <- 7.569587484129203
munsingen.lat <- 46.864709895956004
leaflet(width = "60%", height = "400px") %>%
  addTiles(group = 'OSM') %>%
  addControl("Munsingen necropolis", position = "bottomright") %>%
  addProviderTiles(providers$Esri.WorldImagery, group='Esri.WorldImagery') %>%
  addMarkers(munsingen.long,
             munsingen.lat,
             label = "Munsingen necropolis") %>%
  addLayersControl(
    baseGroups = c('OSM', 'Esri.WorldImagery')) %>%
  addScaleBar(position = "bottomleft")

3.2.2 Plots 2D

With the {plotly} package

3.2.3 Plots 3D

With the {rgl} package

3D scatterplots

4 Export document

Export R Markdown in:

  • HTML
    • Natively. this R Markdown document/webpage
  • PDF
    • Use LaTeX syntax, you need to install the {tinytex} package [Xie19]
  • LaTex
    • in the YAML header:
    out_put: pdf_document 
        keep_tex: true

  Exists a lot of online apps making the conversions easier: Pandoc converter, Word to HTML, etc.

5 Publishing on platforms

6 Practice

  1. Use 1_Rmarkdown_Theory.Rmd as a model (copy/paste code snipet, Mardown syntax, etc.):
  1. 2_Rmarkdown_Practice gives an example of the desired structure of the practice part:
  1. references.bib is the document where you will add the bibliographic refences of the practice part. Google Scholar is a nice tool to copy/paste BibTex references, e.g. this reference:
  • choose a dataset of the {archdata} package (e.g. ‘Handaxes’), you will have to analyse these data/reuse the code you have already created (run ?archdata to see the list of these dataset)

References

Xie, Yihui. 2022. “Knitr. Elegant, Flexible, and Fast Dynamic Report Generation with r.” https://yihui.org/knitr/.
Xie, Yihui, Christophe Dervieux, and Emily Riederer. 2020. R Markdown Cookbook. Chapman; Hall/CRC. https://bookdown.org/yihui/rmarkdown-cookbook/.

  1. This is the first footnote.↩︎

  2. Here’s one with multiple paragraphs and code.

    Indent paragraphs to include them in the footnote.

    { my code }

    Add as many paragraphs as you like.↩︎